var StrategyTypes = require('../constants').StrategyTypes;
var OnlineStatus = require('../constants').OnlineStatus;
var ServiceType = require('../constants').ServiceType;

var allStrategies = {};
allStrategies[StrategyTypes.ONLINE_RANDOM] = onlineRandom;


/**
 * 返回对应策略名称的过滤函数
 * @param strategyName
 * @returns {Function}
 */
module.exports = function (strategyName) {
  return allStrategies[strategyName] || allStrategies[StrategyTypes.ONLINE_RANDOM];
};

/**
 * 随机返回在线客服，如果没有在线客服，返回客服主账号
 * @param store
 * @param statusList
 * @returns {*}
 */
function onlineRandom(store, statusList) {

  // 上一次的客服
  var lastServiceUserId = localStorage.getItem('_serv_of_' + store.storeId);
  var lastService = null;

  var services = store.services;
  console.log('所有客服', services);

  // 增加在线状态
  services.forEach(function (service) {
    for (var i = 0, len = statusList.length; i < len; i++) {
      var status = statusList[i];
      if (!status) {
        continue;
      }

      if (status.userId === service.id) {
        service.online = status.status === OnlineStatus.ONLINE;
      }
    }
  });

  // 在线客服
  var resultServices = store.services.filter(function (service) {
    if (lastServiceUserId === service.id) {
      lastService = service;
    }
    return service.online;
  });

  console.log('上一次客服', lastService);

  // 如果上一次客服在线，选择上一次客服
  if (lastService && lastService.online) {
    return lastService;
  }

  // 如果没有客服在线，离线消息到主客服
  if (!resultServices.length) {
    resultServices = store.services.filter(function (service) {
      return service.isMaster;
    });
  }

  // 如果没有主客服和在线客服，取所有客服
  if (!resultServices.length) {
    resultServices = store.services;
  }

  if (!resultServices.length) {
    return null;
  }

  // 随机返回在线账号，如果没有在线账号，随机返回主账号，如果没有主帐号，随机所有帐号
  var pos = Math.floor(Math.random() * resultServices.length);
  var result = resultServices[pos];
  localStorage.setItem('_serv_of_' + store.storeId, result.id);
  return result;
}
